#include "EasyThread.h"
#if (defined(WIN32) || defined(WIN64))
#include <process.h>
#else
#include <pthread.h>
#endif

//EASYTHREAD_DECLARE(CEasyThread::SDThreadFunc) (void * arg)
//{
//    CEasyThread *pThread = static_cast<CEasyThread*>(arg);
//	if (pThread != NULL)
//	{
//		//pThread->ThrdProc();
//	}
//    return 0;
//}
//

EASYTHREADID  SDGetThreadId()
{
#if (defined(WIN32) || defined(WIN64))
    return ::GetCurrentThreadId();
#else
    return pthread_self();
#endif  //WIN32
}

CEasyThread::CEasyThread()
    :m_bstart(false)
{
    m_handle = EASYINVALID_HANDLE;
    m_tid = 0;
}

CEasyThread::~CEasyThread()
{
    if (m_handle != EASYINVALID_HANDLE)
    {
        //SDThreadCloseHandle(m_handle);
        m_handle = EASYINVALID_HANDLE;
    }
}

bool  CEasyThread::start(PFThrdProc pthrdProc, void * pArg, bool bSuspend /*= false*/)
{
	if (!m_bstart)
	{
		m_handle = EasyCreateThread(NULL, pthrdProc, pArg, &m_tid, bSuspend);
		if (EASYINVALID_HANDLE == m_handle)
		{
			m_bstart = false;
			return false;
		}
		m_bstart = true;
	}
    return true;
}
void  CEasyThread::wait()
{
    if(m_bstart)
    {
        m_bstart = false;
        EasyThreadWait(m_handle);
    }
}


void  CEasyThread::terminate()
{
    if(m_bstart)
    {
        EasyThreadTerminate(m_handle);
        this->onTerminated();
        m_bstart = false;
    }
}

EASYHANDLE  EasyCreateThread(SThreadAttr * pAttr, PFThrdProc pThrdProc,
                              void * pParam, EASYTHREADID * pThreadId/* = NULL*/, bool bSuspend /*= false*/)
{
#if (defined(WIN32) || defined(WIN64))
    int thrdFlag = bSuspend ? CREATE_SUSPENDED : 0;
    // CreateThread(NULL, 0, pThrdProc, pParam, thrdFlag, pThreadId);
    return (EASYHANDLE)_beginthreadex(NULL, 0, pThrdProc, pParam, thrdFlag, pThreadId);
#else
    if (0 != pthread_create((pthread_t*)pThreadId, NULL, pThrdProc, pParam))
    {
        return EASYINVALID_HANDLE;
    }
    return *pThreadId;
#endif // 
}

void  CEasyThread::setAttribute(SThreadAttr * pAttr)
{
    EasySetThreadAttr(m_handle, pAttr);
}

SThreadAttr *   CEasyThread::getAttribute()
{
    return EasyGetThreadAttr(m_handle);
}
void  EasyThreadCloseHandle(EASYHANDLE handle)
{
    EasyCloseHandle(handle);
}

INT32   EasyThreadWait(EASYHANDLE handle)
{
#if (defined(WIN32) || defined(WIN64))
    return ::WaitForSingleObject(handle, INFINITE);
#else
    return pthread_join(handle,NULL);
#endif //
}

void  EasyThreadTerminate(EASYHANDLE handle)
{
#if (defined(WIN32) || defined(WIN64))
    TerminateThread(handle, 0);
    CloseHandle(handle);
#else
    pthread_cancel(handle);
#endif
}

void  EasySetThreadAttr(EASYHANDLE,SThreadAttr * pAttr)
{

}

SThreadAttr*  EasyGetThreadAttr(EASYHANDLE)
{
    return NULL;
}


